package com.freewater.library.lending.book.model;

import com.freewater.library.catalogue.model.BookRepository;
import com.freewater.library.common.domain.DomainException;
import com.freewater.library.lending.book.model.event.BookInstanceArrivedEvent;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.Validate;

@RequiredArgsConstructor
public class BookInstanceFactory {

    private final BookRepository bookRepository;
    private final BookInstanceRepository bookInstanceRepository;

    public BookInstance createBookInstance(String isbn, String qrCode) {
        Validate.notBlank(isbn, "ISBN不能为空");
        Validate.notBlank(qrCode, "二维码不能为空");
        boolean isbnExists = this.bookRepository.exists(isbn);
        if (!isbnExists) {
            throw new DomainException("无效的ISBN");
        }
        boolean qrCodeExists = this.bookInstanceRepository.exists(qrCode);
        if (qrCodeExists) {
            throw new DomainException("二维码已存在");
        }
        BookInstance bookInstance = new BookInstance(qrCode, isbn);
        BookInstanceArrivedEvent event =
                new BookInstanceArrivedEvent(bookInstance.getQrCode(), bookInstance.getIsbn());
        bookInstance.raiseEvent(event);
        return bookInstance;
    }
}
